package main

import (
	"crypto/rand"
	"database/sql"
	"fmt"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"log"
	"time"
)

func useRedis() {
	addr := "127.0.0.1:6379"
	password := ""
	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: password,
		DB:       0,
	})
	_, err := client.Ping().Result()
	if err != nil {
		fmt.Println("redis ping error ")
	}
	fmt.Println("ping success")
	client.Do("set", "key", "yzp")
	val := client.Do("get", "key").Val()
	fmt.Println(val)
	err = client.Close()
	if err != nil {
		return
	}
}

type MyUser struct {
	Id         int       `json:"id"`
	Name       string    `json:"name"`
	Password   string    `json:"password"`
	Age        int       `json:"age"`
	ReadBooks  string    `json:"read_books"`
	CreateTime time.Time `json:"create_time"`
	Comment    string    `json:"comment"`
	UpdateTime time.Time `json:"update_time"`
}

func (MyUser) TableName() string {
	return "my_user"
}

func mysqlOperate() {
	dataSource := "root:123456@tcp(localhost:3306)/gotest"
	db, err := sql.Open("mysql", dataSource)
	if err != nil {
		panic(err)
	}
	defer db.Close()

	db.SetConnMaxLifetime(time.Minute * 3)
	db.SetMaxOpenConns(10)
	db.SetMaxIdleConns(10)
	db.SetConnMaxIdleTime(time.Minute * 3)

	err = db.Ping()
	if err != nil {
		panic(err)
	} else {
		fmt.Println("connect mysql success")
	}

	sqlStr := "select id,name,age from my_user where id=?"
	var user MyUser
	err = db.QueryRow(sqlStr, 1).Scan(&user.Id, &user.Name, &user.Age)
	if err != nil {
		fmt.Printf("scan error %v\n", err)
	} else {
		fmt.Printf("id:%d name:%s age:%d \n", user.Id, user.Name, user.Age)
	}

	sqlStr = "insert into my_user(id,name,age) values(?,?,?)"
	ret, err := db.Exec(sqlStr, 3, "Bob", 99)
	if err != nil {
		fmt.Printf("insert failed, error: %v \n", err)
	} else {
		id, err := ret.LastInsertId()
		if err != nil {
			panic(err)
		} else {
			fmt.Printf("insert success,last id is : %d \n", id)
		}
	}

	sqlStr = "update my_user set age=? where id = ?"
	ret, err = db.Exec(sqlStr, 18, 2)
	if err != nil {
		fmt.Printf("update failed, err:%v \n", err)
	} else {
		n, err := ret.RowsAffected()
		if err != nil {
			fmt.Printf("get RowsAffected failed, err:%v \n", err)
		} else {
			fmt.Printf("update success, affected rows:%d \n", n)
		}
	}

	sqlStr = "select id,name,age from my_user where id>?"
	rows, err := db.Query(sqlStr, 0)
	if err != nil {
		panic(err)
	} else {
		defer rows.Close()
		for rows.Next() {
			err = rows.Scan(&user.Id, &user.Name, &user.Age)
			if err != nil {
				panic(err)
			}
			fmt.Printf("id:%d,name:%s,age:%d\n", user.Id, user.Name, user.Age)
		}
	}
}

func genUUID() {
	bytes := make([]byte, 16)
	_, err := rand.Read(bytes)
	if err != nil {
		log.Fatal(err)
		panic(err)
	}
	uuid := fmt.Sprintf("%x-%x-%x-%x-%x", bytes[0:4], bytes[4:6], bytes[6:8], bytes[8:10], bytes[10:])
	fmt.Println(uuid)
}

//func main() {
//	ch := make(chan struct{})
//	go func() {
//		select {
//		case v, ok := <-ch:
//			if !ok {
//				fmt.Println("chan ch is closed")
//			}
//			fmt.Println(v)
//		}
//
//	}()
//	close(ch)
//	time.Sleep(time.Second)
//	fmt.Println(<-ch)
//}

func sqlOther() {
	dataSource := "root:123456@tcp(localhost:3306)/gotest?charset=utf8&parseTime=True&loc=Local"
	db, err := gorm.Open("mysql", dataSource)
	if err != nil {
		panic(err)
	} else {
		fmt.Printf("当前时间,%s\t", time.Now().Format("2006-01-02 15:04:05"))
		fmt.Println("连接数据库成功")
	}
	defer db.Close()
	//user := &MyUser{Age: 45, Id: 5, Name: "sd", ReadBooks: "jksd", Comment: "sds",
	//	CreateTime: time.Now(), UpdateTime: time.Now()}
	//db.Create(user)
	//if db.NewRecord(user) {
	//	fmt.Println("写入失败")
	//} else {
	//	fmt.Println("写入成功")
	//}

	users := make([]*MyUser, 0)
	db.Model(&MyUser{}).Find(&users)
	fmt.Printf("%v\n", users)

	//var user1, user2 MyUser
	//db.First(&user1)
	//bs, err := json.Marshal(user1)
	//if err != nil {
	//	panic(err)
	//}
	//var out bytes.Buffer
	//json.Indent(&out, bs, "", "\t")
	//fmt.Printf("%v\n", out.String())
	//
	//db.First(&user2, "id=?", 2)
	//bs, err = json.Marshal(&user2)
	//if err != nil {
	//	panic(err)
	//}
	//out = *new(bytes.Buffer)
	//json.Indent(&out, bs, "", "\t")
	//fmt.Printf("%v\n", out.String())
	//
	//var count int
	//db.Model(&MyUser{}).Count(&count)
	//fmt.Println(count)

	//m := &MyUser{}
	//db.Find(m)
	//m.Name = "longqic"
	//db.Save(m)
	//fmt.Println(m)

	user3 := &MyUser{}
	db.Find(user3)
	db.Model(user3).Update("name", "hello")
}

func deleteUser() {
	dataSource := "root:123456@tcp(localhost:3306)/gotest?charset=utf8&parseTime=True&loc=Local"
	db, err := gorm.Open("mysql", dataSource)
	if err != nil {
		panic(err)
	}
	u := &MyUser{Id: 3}
	db.Delete(u)
	db.Delete(&MyUser{}, "id=?", 2)
}
